// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import { postAnswer } from '@/services/answer'
import type { NextApiRequest, NextApiResponse } from 'next'

type Data = {
  name: string
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  console.log('method: ', req.method)
  if (req.method !== 'POST') {
    res.status(200).json({ errno: -1, msg: 'Method 错误' })
  }

  // 提交到服务端
  const answerInfo = genAnswerInfo(req.body)
  console.log(answerInfo)
  try {
    // 提交到服务端
    const resData = await postAnswer(answerInfo)
    if (resData.errno === 0) {
      // 如果提交成功了
      res.redirect('/success')
    } else {
      res.redirect('/fail')
    }
  } catch (err) {
    // 如果提交失败了
    res.redirect('/fail')
  }
  res.status(200).json({ errno: 0 })
}

function genAnswerInfo(reqBody: any) {
  const answerList: any[] = []
  Object.keys(reqBody).forEach(key => {
    if (key === 'questionId') return
    answerList.push({ componentId: key, value: reqBody[key] })
  })

  return {
    questionId: reqBody.questionId || '',
    answerList,
  }
}
